// my-course.js
import Toast from '@vant/weapp/toast/toast';
import { getMyCourseList, dropCourse, getTimetable } from '../../utils/api-v2';

Page({
  data: {
    stats: {
      totalCount: 0,
      totalCredit: 0
    },
    courseList: []
  },

  onLoad() {
    this.loadMyCourses();
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.loadMyCourses();
  },

  // 加载我的课程
  loadMyCourses() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
      duration: 0
    });

    // 同时调用两个接口：选课记录 + 课表信息
    Promise.all([
      getMyCourseList(),  // 获取选课记录（成绩等）
      getTimetable()      // 获取课程详细信息（时间、地点）
    ])
      .then(([courseRes, timetableRes]) => {
        Toast.clear();
        
        let courseList = courseRes.data || [];
        let timetableList = timetableRes.data || [];
        
        console.log('========== 选课记录 API 返回 ==========');
        console.log('选课记录:', JSON.stringify(courseRes, null, 2));
        console.log('========== 课表信息 API 返回 ==========');  
        console.log('课表信息:', JSON.stringify(timetableRes, null, 2));
        
        // 创建课程名称到课表信息的映射
        const timetableMap = {};
        timetableList.forEach(course => {
          const key = course.courseName || course.name;
          if (key) {
            timetableMap[key] = {
              time: course.time,
              location: course.location || course.classroom,
              teacherName: course.teacherName
            };
          }
        });
        
        console.log('课表映射:', timetableMap);
        
        // 合并选课记录和课表信息
        courseList = courseList.map(item => {
          // 查找有效的 ID 字段
          const validId = item.studentCourseId || item.courseId || item.cid || item.course_id;
          
          // 从课表信息中获取时间和地点
          const timetableInfo = timetableMap[item.courseName] || {};
          
          // 格式化时间: "2-2-4" => "周二 2-5节"
          let formattedTime = timetableInfo.time || item.time || item.courseTime || '未安排';
          if (formattedTime && formattedTime !== '未安排') {
            formattedTime = this.formatTime(formattedTime);
          }
          
          // 补充缺失的字段，从课表信息补充
          return {
            ...item,
            id: validId,
            time: formattedTime,
            location: timetableInfo.location || item.location || item.courseLocation || '待定',
            teacherName: timetableInfo.teacherName || item.teacherName,
            selectDate: item.selectDate || item.createTime || new Date().toLocaleDateString()
          };
        });
        
        console.log('========== 合并后的课程数据 ==========');
        console.log('第一个课程合并后:', courseList[0]);
        console.log('id 值:', courseList[0]?.id);
        console.log('time 值:', courseList[0]?.time);
        console.log('location 值:', courseList[0]?.location);
        console.log('========================================');

        // 同步到本地存储（用于课表显示）
        wx.setStorageSync('myCourses', courseList);

        // 计算统计数据
        const totalCount = courseList.length;
        const totalCredit = courseList.reduce((sum, item) => sum + (item.credit || 0), 0);

        this.setData({
          courseList,
          stats: {
            totalCount,
            totalCredit
          }
        });
      })
      .catch((err) => {
        Toast.clear();
        console.error('加载课程数据失败:', err);
        Toast.fail('加载失败，请稍后重试');
      });
  },

  // 退选课程
  dropCourse(e) {
    const { id, name } = e.currentTarget.dataset;
    
    console.log('===== 退选调试 =====');
    console.log('点击退选，id:', id, 'name:', name);
    console.log('dataset:', e.currentTarget.dataset);
    console.log('当前课程列表:', this.data.courseList);
    if (this.data.courseList && this.data.courseList.length > 0) {
      console.log('第一个课程:', this.data.courseList[0]);
      console.log('第一个课程的所有字段:', Object.keys(this.data.courseList[0]));
    }
    console.log('==================');
    
    if (!id) {
      Toast.fail('课程ID不存在');
      return;
    }
    
    wx.showModal({
      title: '确认退选',
      content: `确定要退选《${name}》吗？`,
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          this.confirmDrop(id);
        }
      }
    });
  },

  // 确认退选
  confirmDrop(courseId) {
    console.log('确认退选，courseId:', courseId);
    
    Toast.loading({
      message: '退选中...',
      forbidClick: true,
      duration: 0
    });

    // 调用接口 DELETE /student/course/:id
    dropCourse(courseId)
      .then((res) => {
        Toast.clear();
        Toast.success('退选成功');

        // 从本地存储中删除课程
        let myCourses = wx.getStorageSync('myCourses') || [];
        myCourses = myCourses.filter(course => course.id !== courseId);
        wx.setStorageSync('myCourses', myCourses);

        // 重新加载课程列表
        setTimeout(() => {
          this.loadMyCourses();
        }, 1000);
      })
      .catch((err) => {
        Toast.clear();
        Toast.fail(err.msg || '退选失败');
        console.error('退选失败:', err);
      });
  },

  // 去选课
  goToSelectCourse() {
    wx.navigateTo({
      url: '/pages/select-course/select-course'
    });
  },

  /**
   * 格式化时间字符串
   * @param {string} timeStr - 原始时间 "4-5-4"
   * @returns {string} - 格式化后 "周四 5-8节"
   */
  formatTime(timeStr) {
    if (!timeStr) return '未安排';
    
    // 已经是中文格式，直接返回
    if (timeStr.includes('周')) {
      return timeStr;
    }
    
    // 解析 "4-5-4" 格式：周4，第5节开始，上4节课
    const match = timeStr.match(/^(\d+)-(\d+)-(\d+)$/);
    if (match) {
      const day = parseInt(match[1]);
      const startSlot = parseInt(match[2]);
      const duration = parseInt(match[3]);
      const endSlot = startSlot + duration - 1;
      
      const weekDays = ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'];
      const weekDay = weekDays[day] || '周?';
      
      return `${weekDay} ${startSlot}-${endSlot}节`;
    }
    
    return timeStr;
  }
});
